package lambda;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        Test.demo6();
        Test.demo5();
        Test.demo4();
        Test.demo3();
        Test.demo2();
        Test.demo1();
    }

    //复制不同的值，创建一个子列表
    public static void demo6(){
        List<Integer> numbers = Arrays.asList(9,10, 3,4, 7,3, 4);
        List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
        System.out.printf("Original List : %s,  Square Without duplicates : %s %n", numbers, distinct);
    }

    //计算集合元素的最大值、最小值、总和以及平均值
    public static void demo5(){
        List<Integer> primes = Arrays.asList(2,3, 5,7, 11,13, 17,19, 23,29);
        IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
        System.out.println("Highest prime number in List : "+ stats.getMax());
        System.out.println("Lowest prime number in List : "+ stats.getMin());
        System.out.println("Sum of all prime numbers : "+ stats.getSum());
        System.out.println("Average of all prime numbers : "+ stats.getAverage());
    }

    //predicate
    public static void filterTest(List<String> languages, Predicate<String> condition) {
        languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));
    }

    public static void demo4(){
        List<String> languages = Arrays.asList("Java","Python","scala","Shell","R");
        System.out.println("Language starts with J: ");
        filterTest(languages,x -> x.startsWith("J"));
    }

    //map reduce
    public static void demo3(){
        List<Double> list =Arrays.asList(25.0,22.0,1.0);

        //map
        list.stream().map(p->p+2.0).forEach(p-> System.out.println(p));

        //map reduce
        double re=list.stream().map(p->p+2.0).reduce((x,y)->x+y).get();
        System.out.println(re);

        //filter map reduce
        list.stream().filter(x->x>5.0).map(p->p+2.0).forEach(p-> System.out.println(p));

    }

    //集合
    public static void demo2(){
        List<String> list = Arrays.asList("hxl","gyd","hww");

        list.forEach(System.out::println);
        list.forEach(p-> System.out.println(p));
    }

    //匿名内部类
    public static void demo1(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("***线程启动***");
            }
        }).start();

        //替换
        new Thread(()-> System.out.println("***简洁线程启动***")).start();

        //扩展
        new Thread(()->{
            System.out.println("do first");
            System.out.println("do end");
        }).start();
    }
}
